/*******************************************************************************
 * Copyright (c) 2007 - 2025 Maxprograms.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 1.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/org/documents/epl-v10.html
 *
 * Contributors:
 *     Maxprograms - initial API and implementation
 *******************************************************************************/

class TermOnlinePlugin {

    electron = require('electron');
    searchText: string = '';
    sourceLang: string = '';
    tgtLangs: string[] = [];

    constructor() {
        this.electron.ipcRenderer.send('get-theme');
        this.electron.ipcRenderer.on('set-theme', (event: Electron.IpcRendererEvent, theme: string) => {
            (document.getElementById('theme') as HTMLLinkElement).href = theme;
        });
        
        this.electron.ipcRenderer.send('get-selection');
        this.electron.ipcRenderer.on('set-selected-text', (event: Electron.IpcRendererEvent, arg: { selected: string, lang?: string, srcLang: string, tgtLang: string }) => {
            this.searchText = arg.selected;
            if (arg.lang && arg.lang === arg.tgtLang) {
                let tmp: string = arg.srcLang;
                arg.srcLang = arg.tgtLang;
                arg.tgtLang = tmp;
            }
            this.sourceLang = arg.srcLang.indexOf('-') !== -1 ? arg.srcLang.split('-')[0] : arg.srcLang;
            this.tgtLangs = [];
            if (arg.tgtLang) {
                this.tgtLangs = [arg.tgtLang.indexOf('-') !== -1 ? arg.tgtLang.split('-')[0] : arg.tgtLang];
            }
        });
        
        let toolbar: HTMLDivElement = (document.getElementById('toolbar') as HTMLDivElement);
        let termOnlineFrame: HTMLIFrameElement = document.getElementById('termOnlineFrame') as HTMLIFrameElement;
        let loadingDiv: HTMLDivElement = document.getElementById('loading') as HTMLDivElement;
        
        termOnlineFrame.addEventListener('load', () => {
            loadingDiv.style.display = 'none';
            termOnlineFrame.style.display = 'block';
            
            // 如果有选中的文本，尝试填入搜索框
            if (this.searchText) {
                this.fillSearchText();
            }
            
            this.setSize();
        });
        
        document.addEventListener('keydown', (event: KeyboardEvent) => {
            if (event.code === 'Escape') {
                this.electron.ipcRenderer.send('close-termOnlinePlugin');
            }
            if (event.code === 'Enter' || event.code === 'NumpadEnter') {
                // 在术语在线网站中触发搜索
                this.triggerSearch();
            }
        });
        
        (document.getElementById('basic') as HTMLInputElement).addEventListener('click', () => {
            this.loadBasicSearch();
        });
        
        (document.getElementById('advanced') as HTMLInputElement).addEventListener('click', () => {
            this.loadAdvancedSearch();
        });
        
        let toolbarHeight = toolbar.offsetHeight;
        termOnlineFrame.style.height = (window.innerHeight - toolbarHeight) + 'px';
        window.addEventListener('resize', () => {
            termOnlineFrame.style.height = (window.innerHeight - toolbarHeight) + 'px';
        });
        
        // 默认加载基础搜索
        setTimeout(() => {
            this.loadBasicSearch();
        }, 200);
    }

    loadBasicSearch(): void {
        let termOnlineFrame: HTMLIFrameElement = document.getElementById('termOnlineFrame') as HTMLIFrameElement;
        let loadingDiv: HTMLDivElement = document.getElementById('loading') as HTMLDivElement;
        
        loadingDiv.style.display = 'flex';
        termOnlineFrame.style.display = 'none';
        
        // 基础搜索：直接跳转到术语在线首页
        if (this.searchText) {
            // 构建搜索URL，如果有搜索文本则直接搜索
            const searchUrl = `https://www.termonline.cn/search/result?k=${encodeURIComponent(this.searchText)}`;
            termOnlineFrame.src = searchUrl;
        } else {
            termOnlineFrame.src = 'https://www.termonline.cn/';
        }
        
        this.setSize();
    }

    loadAdvancedSearch(): void {
        let termOnlineFrame: HTMLIFrameElement = document.getElementById('termOnlineFrame') as HTMLIFrameElement;
        let loadingDiv: HTMLDivElement = document.getElementById('loading') as HTMLDivElement;
        
        loadingDiv.style.display = 'flex';
        termOnlineFrame.style.display = 'none';
        
        // 高级搜索：跳转到术语在线的高级搜索页面
        termOnlineFrame.src = 'https://www.termonline.cn/search/advance';
        
        this.setSize();
    }

    fillSearchText(): void {
        if (!this.searchText) return;
        
        let termOnlineFrame: HTMLIFrameElement = document.getElementById('termOnlineFrame') as HTMLIFrameElement;
        
        // 尝试多种方式填入搜索文本
        setTimeout(() => {
            try {
                const frameDoc = termOnlineFrame.contentDocument || termOnlineFrame.contentWindow?.document;
                if (frameDoc) {
                    // 查找可能的搜索输入框
                    const searchInputs = [
                        frameDoc.querySelector('input[name="k"]'),
                        frameDoc.querySelector('input[type="search"]'),
                        frameDoc.querySelector('.search-input'),
                        frameDoc.querySelector('#search'),
                        frameDoc.querySelector('.form-control')
                    ];
                    
                    for (const input of searchInputs) {
                        if (input && input instanceof HTMLInputElement) {
                            input.value = this.searchText;
                            input.focus();
                            // 触发输入事件
                            const event = new Event('input', { bubbles: true });
                            input.dispatchEvent(event);
                            break;
                        }
                    }
                }
            } catch (error) {
                console.log('无法访问iframe内容，可能是跨域限制:', error);
            }
        }, 1000);
    }

    triggerSearch(): void {
        let termOnlineFrame: HTMLIFrameElement = document.getElementById('termOnlineFrame') as HTMLIFrameElement;
        
        try {
            const frameDoc = termOnlineFrame.contentDocument || termOnlineFrame.contentWindow?.document;
            if (frameDoc) {
                // 查找搜索按钮
                const searchButtons = [
                    frameDoc.querySelector('button[type="submit"]'),
                    frameDoc.querySelector('.search-btn'),
                    frameDoc.querySelector('.btn-search'),
                    frameDoc.querySelector('#searchBtn')
                ];
                
                for (const button of searchButtons) {
                    if (button && button instanceof HTMLButtonElement) {
                        button.click();
                        break;
                    }
                }
            }
        } catch (error) {
            console.log('无法触发搜索，可能是跨域限制:', error);
        }
    }

    setSize(): void {
        setTimeout(() => {
            this.electron.ipcRenderer.send('set-height', { 
                window: 'termOnlinePlugin', 
                width: document.body.clientWidth, 
                height: document.body.clientHeight 
            });
        }, 200);
    }
} 